<template>
  <div class="groupNameDetail" id="groupNameDetail">
    <!-- 功能按钮 -->
    <div class="groupNameDetail_button">
      <!-- <div class="groupSelect">
        所属分组：
        <a-select v-model:value="groupType" @change="groupChange" :options="groupOptions"></a-select>
      </div> -->
      <div class="searchContent">
        <a-input v-model:value="keyWord" placeholder="搜索用户名/手机号/邮箱号" style="width: 232px;padding-right: 48px;">
          <template #suffix>
            <i class="iconfont icon-search" @click="onSearch"></i>
          </template>
        </a-input>
      </div>
    </div>
    <!-- 表格展示部分 -->
    <baseTable :columns="columns.auditedManageColumn" :dataSource="configData.records" :isSelect="true" :scroll="scroll"
      ref="hotBaseTables" :isShowPagination="isShowPagination" :showCheckDelete="showCheckDelete"
      :total="configData.total" @deleteRecord="deleteSelectedAll" @changePage="changePage">
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.ellipsis">
          <table-tool-tip :text="text" :column="column"></table-tool-tip>
        </template>
        <template v-if="column.dataIndex === 'isEnabled'">
          <a-switch @click="switchChange(record)" size="small" v-model:checked="record.isEnabled" />
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a class="eidtRecords" :class="{ disable: !btnPerm.includes('lookAuditAble') }" @click="showDetail(record)">{{ record.oparation[0] }}</a>
          <a-popconfirm placement="topRight" @confirm="confirmDelete(record)">
            <template #title>
              <p style="width: 197px">
                移除后，该会员将变成无会员组的状态，可能会导致其部分访问受限，请尽快对该会员进行分组调整
              </p>
            </template>
            <a>{{ record.oparation[2] }}</a>
          </a-popconfirm>
        </template>
      </template>
      <template #otherOpration>
        <a-button @click="toPass(true)" :style="{ 'margin-left': '8px' }" :disabled="!rowSelection.length || !btnPerm.includes('passAble')">通过</a-button>
        <a-button @click="toPass(false)" :style="{ 'margin-left': '8px' }" :disabled="!rowSelection.length || !btnPerm.includes('noPassAble')">不通过</a-button>
      </template>
    </baseTable>

    <!-- 新建会员-->
    <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title" :buttons="buttons"
      @handleOk="buttonMessage" @handleCancle="isVisible = false" class="sensitive_modal">
      <template v-slot:body>
        <a-form name="advanced_search" autoComplete="off" style="min-height:300px">
          <div class="item-member">
            <div class="left" :style="getWidth()">会员编号：</div>
            {{ detailRecord.id }}
          </div>
          <div class="item-member">
            <div class="left" :style="getWidth()"> 用户名：</div>
            {{ detailRecord.userName }}
          </div>
          <div class="item-member">
            <div class="left" :style="getWidth()"> 会员头像：</div>
            {{ detailRecord.headImageUrl }}
          </div>
          <template v-for="(item, index) in memberFormState">
            <div class="basic-item">
              <component :is="comps[item.componentName]" :index="index" :element="item" v-if="item" />
            </div>
          </template>
        </a-form>
      </template>
    </base-modal>
    <!-- 审核不通过模态框 -->
    <base-modal :width="modAlPropsPass.width" :isVisible="isShowReason" :title="modAlPropsPass.title"
      :buttons="buttonsPass" @handleOk="buttonPass()" @handleCancle="isShowReason = false">
      <template v-slot:body>
        <a-form ref="noPassFrom" autoComplete="off" class="reason-modal" :model="formState" name="reason-form">
          <a-form-item :name="['reason', 'value']" :label="formState.reason.label" :rules="[formState.reason.rule]">
            <a-textarea style="position: relative; height: 80px;" v-model:value="formState.reason.value"
              placeholder="不超过200个字" show-count :maxlength="200" />
          </a-form-item>
        </a-form>
      </template>
    </base-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch, nextTick, createVNode } from "vue";
import baseTable from "@/components/table/baseTable.vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import { useRoute } from "vue-router";
import columns from "@/components/table/tableConfig/columnsName";
import { getTableScroll } from "@/components/table/tableConfig/table";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import { comps } from '@/components/draggable/exportComp'
import baseModal from "@/components/modal/baseModal.vue";
import { Modal, message } from "ant-design-vue";
import request from "@/api/index";
import { cloneDeep } from "lodash";
import { scrollType, modeProp } from "@/type.d";
import { encrypt3DES, decrypt3DES } from "@/utils/cryptojs";
import {routerPerm} from '@/utils/common';
// type
type configDataType = {
  total: number;
  size: number;
  records: any[];
};
interface dataSourceType {
  [propName: string]: any;
}
interface FormState {
  groupNameDetail: dataSourceType;
  password: string;
  remember: boolean;
}

//data
const btnPerm = ref<any[]>([]);
const { query } = useRoute();

const memberFormState = ref<dataSourceType[]>([]);
const instanceItems = ref<dataSourceType[]>([]);
let detailData = reactive<dataSourceType>({});
let detailRecord = reactive<dataSourceType>({});
const noPassFrom = ref<any>("noPassFrom");
const groupOptions = ref<dataSourceType[]>([{ value: "全部" }]);
let scroll: scrollType = reactive({ y: "", isFixed: false }); // 表单滚动设置
const isShowPagination = true; // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义全选和删除

//表格数据
let configData = reactive<configDataType>({ total: 0, size: 10, records: [] });
const hotBaseTables = ref<any>(null);
const addNewTables = ref<any>(null);
let rowSelection = ref<(string | number)[]>([]);
let moveRowSelection = ref<(string | number)[]>([]);
const deleteArr = ref<(string | number)[]>([]);
const memberModelId = ref<number | null>(null);
// 模态框数据
const isAdd = ref<boolean>(false); //判断是新家、编辑或者批量上传来复用模态框
const isVisible = ref<boolean>(false);
const isShowReason = ref<boolean>(false);
const keyWord = ref<string>("");
let datas = reactive<dataSourceType>({});
let modAlProps: modeProp = reactive({
  width: "L",
  title: "会员详情",
});
let modAlPropsPass: modeProp = reactive({
  width: "M",
  title: "审核不通过",
});

const formState = reactive<dataSourceType>({
  reason: {
    value: "",
    rule: {
      required: true,
      trigger: ["blur"],
      message: '原因不能为空！',
    },
    label: "原因",
  },
});
const onSearch = async () => {
  //搜索获取数据参数配置
  datas.keyWord = keyWord.value,
    getRecord();
};

const switchChange = (record: any) => {
  if (!record.isDefault) {
    configData.records.length &&
      configData.records.forEach((item) => {
        item.isDefault = item.id == record.id ? true : false;
      });
    message.warn("默认分组无法转换为普通分组");
    return;
  }
  let params: dataSourceType = {
    id: record.id,
  };
  request
    .fetchMemberGroupDefault(params)
    .then((res: any) => {
      if (res.code == "00000 00000") {
        getRecord();
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};


//获取最大的label的宽度
const getWidth = () => {
  let nameList: any[] = ['会员编号', '用户名', '会员头像'];
  let labelLength: any[] = [];
  nameList.forEach((item: any) => {
    labelLength.push(item.length || 0);
  });
  let maxLength = Math.max(...labelLength);
  return { width: (maxLength + 1) * 14 + "px" };
};

const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改
const buttonsPass = ref<dataSourceType[]>([
  {
    text: "提交",
    "html-type": "submit",
    keepAlive: true,
  },
]); //模态框button按钮个数和文案修改

// computed
rowSelection = computed(() => {
  return hotBaseTables.value.selectedRowKeys;
});

moveRowSelection = computed(() => {
  return addNewTables.value.selectedRowKeys;
});

//methods

//对话框的确定保存
const buttonPass = async () => {
  noPassFrom.value
    .validate()
    .then(() => {
      let ids = rowSelection.value.length ? rowSelection.value : [detailRecord.id];
      const params = {
        ids,
        isPass: false,
        reason: formState.reason.value
      };
      request.fetchMemberAudit(params)
        .then((res: any) => {
          if (res.code == "00000 00000") {
            isVisible.value = false
            isShowReason.value = false
            formState.reason.value = '';
            getRecord();
            message.success(res.message);
          } else {
            message.error(res.message);
          }
        })
        .catch((err: any) => {
          throw new Error
        })
    }).catch(() => { });

}


const showDetail = async (record: dataSourceType) => {
  if(!btnPerm.value.includes('lookAuditAble')) return
  //编辑会员数据
  detailData = await request.fetchMemberDetail({ id: record.id });
  memberFormState.value.length && memberFormState.value.forEach((item: dataSourceType) => {
    detailData.instance?.instanceItems && detailData.instance.instanceItems.length && detailData.instance.instanceItems.forEach((dItem: dataSourceType) => {
      if (item.param === 'password' && item.param === dItem.field) {
        item.value = decrypt3DES(dItem.value)
      } else if (item.param === dItem.field && item.param !== 'password') {
        item.value = dItem.value
      }
    })
    item.disabled = true
  })
  detailRecord = record
  isAdd.value = true;
  isVisible.value = true;
  buttons.value = [
    {
      text: "审核不通过",
      "html-type": "submit",
      keepAlive: true,
      color: '#FF4D4F',
      disabled: !btnPerm.value.includes('noPassAble'),
    },
    {
      text: "审核通过",
      "html-type": "submit",
      keepAlive: true,
      disabled: !btnPerm.value.includes('passAble')
    },
  ];
};

// 新添或编辑会员分组调取接口
const buttonMessage = async (msg: dataSourceType) => {
  let params = {}
  if (msg.text === '审核不通过') {
    if(!btnPerm.value.includes('noPassAble')) return
    params = {
      // groupId: '',
      ids: [detailRecord.id],
      isPass: false,
      reason: formState.reason.value
    };
    isShowReason.value = true
    isVisible.value = false
    return
  } else {
    if(!btnPerm.value.includes('passAble')) return
    params = {
      // groupId: '',
      ids: [detailRecord.id],
      isPass: true,
      reason: ""
    };
  }
  console.log('haha ');
  
  request.fetchMemberAudit(params)
    .then((res: any) => {
      if (res.code == "00000 00000") {
        isVisible.value = false
        isShowReason.value = false
        getRecord();
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error
    })
}

// 删除单个会员
const confirmDelete = async (item: any) => {
  deleteArr.value = [item.id];
  deleteRecords(deleteArr.value);
};

//删除已选所有会员
const deleteSelectedAll = async () => {
  let keys = rowSelection.value;
  Modal.confirm(
    Object.assign({}, msgModal.confirm, {
      title: "是否将所选的会员从其分组中移除？",
      content:
        "移除后，所选会员将变成无会员组的状态，可能会导致所选会员的部分访问受限，请尽快对会员进行分组调整",
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON",

      }),
      okText: "确定",
      onOk: async () => {
        await deleteRecords(keys);
        Modal.destroyAll();
      },
      onCancel() {
        Modal.destroyAll();
      },
    })
  );
};

const deleteRecords = async (keys: (string | number)[] = []) => {
  // 调接口删除会员
  await request.fetchMemberDelete({ ids: keys }).then((res: any) => {
    if (res.code == "00000 00000") {
      message.success(res.message);
      getRecord();
    } else {
      message.error(res.message);
    }
  });
};

const getRecord = async () => {
  // 获取会员表格数据
  const data: {} = {
    pageNumber: datas.pageNumber || 0,
    pageSize: datas.pageSize || 10,
    keyWord: datas.keyWord || query.userName,
    pageSort: "",
  };
  const groupData = (await request.fetchMemberAuditingPage(data)) || {};
  let reqData = groupData;
  let sourceData = reactive({});
  const records: any[] = [];
  reqData?.records?.map((item: any, index: number) => {
    sourceData = {
      ...item,
      createTime: item.createTime,
      groupId: item.groupId,
      groupName: item.groupName,
      isEnabled: item.isEnabled,
      lastLoginTime: item.lastLoginTime,
      nickName: item.nickName,
      auditStatus: item.auditStatus === 0 ? '审核中' : item.auditStatus === 1 ? '审核成功' : item.auditStatus === 2 ? '审核不通过' : '',
      userPhone: item.userPhone,
      id: item.id,
      oparation: ["查看注册信息并审核"],
    };

    records.push(sourceData);
  });
  configData.total = reqData.total;
  configData.size = reqData.size;
  configData.records = records;
  hotBaseTables.value.selectedRowKeys = [];
  nextTick(() => {
    scroll.y = getTableScroll(74, "groupNameDetail").y;
    scroll.isFixed = getTableScroll(74, "groupNameDetail").isFixed;
  });
};

//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {

  datas.pageNumber = data.pageCurrent;
  datas.pageSize = data.pageSize;
  getRecord();
};

const getGroup = async () => {
  groupOptions.value = await request.fetchMemberGroupList();
  groupOptions.value.map((item: any) => (item.value = item.name));
};

//批量通过和不通过
const toPass = (isPass: boolean) => {
  if (!isPass && !formState.reason.value) {
    isShowReason.value = true
    return
  }
  let ids = rowSelection.value;
  const params = {
    ids,
    isPass,
    reason: ""
  };
  request.fetchMemberAudit(params)
    .then((res: any) => {
      if (res.code == "00000 00000") {
        formState.reason.value = '';
        getRecord();

        message.success(res.message);
      } else {
        formState.reason.value = '';
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error
    })
}

//获取详情
const getDetail = async () => {
  const data = await request.fetchModelMemberModel()
  memberModelId.value = data.id
  memberFormState.value = JSON.parse(data.enableJson)
}

//watch
watch(() => memberFormState.value, (newVal, oldVal) => {
  instanceItems.value = []
  newVal.length && newVal.forEach((item: dataSourceType) => {
    let obj: dataSourceType = {}
    if (item.param === 'password') {
      obj.field = item.param;
      obj.value = encrypt3DES(item.value)
    } else {
      obj.field = item.param;
      obj.value = item.value || '';
    }
    instanceItems.value.push(obj)
  })
}, { deep: true })

//onmounted
onMounted(() => {
  btnPerm.value = routerPerm()
  getRecord();
  getDetail();
  getGroup();
});
</script>
<style lang="scss" scoped>
.groupNameDetail {
  width: 100%;
  height: calc(100% - 72px);
  padding: 16px;
  background-color: #fff;

  .groupNameDetail_button {
    padding-bottom: 24px;
    display: flex;

    .addButton {
      display: flex;
      align-items: center;
      margin-right: 8px;

      .iconadd {
        font-size: 24px;
        margin-right: 4px;
      }
    }

    .importButton {
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      margin-right: 8px;
    }

    .groupSelect {
      margin-left: auto;
    }

    .statusSelect {
      margin-left: 16px;
    }

    .searchContent {
      margin-right: 0px;

      .icon-search {
        font-size: 20px;
        color: rgba(0, 0, 0, 0.45);
        position: absolute;
        right: 12px;
        top: 0px;
      }
    }
  }

  :deep(.ant-table-thead .ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    margin-right: 16px;
  }

  .eidtRecords {
    margin-right: 0px;
  }

  .eidtRecords1 {
    margin-right: 16px;
  }
}

.reason-modal {
  ::v-deep(.ant-form-item) {
    width: 604px;
    display: flex;

    .ant-form-item-control {
      width: 538px;
      margin-left: 4px;
      flex: unset;
    }

    .ant-form-item-label {
      flex-grow: 0;
      width: 50px;
      text-align: right;
    }
  }

}

.item-member {
  padding: 0 10px;
  display: flex;
  align-items: center;
  max-width: 100%;
  height: 22px;
  color: rgba(0, 0, 0, 0.85);
  font-size: 14px;
  margin-left: 32px;
  margin-bottom: 24px;

  .left {
    text-align: right;
  }
}

.add-item {
  .header-content {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 24px;

    ::v-deep(.group-select .ant-select) {
      width: 288px;
    }

    .searchContent {
      margin-left: 16px;
      width: 192px;
      height: 32px;

      ::v-deep(.ant-input-affix-wrapper) {
        height: 32px;
      }
    }
  }
}

.reason-con {
  display: flex;
  font-size: 14px;
  font-family: PingFang SC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
  line-height: 14px;
}

.move-item {
  display: flex;
  flex-direction: column;

  span {
    margin-bottom: 8px;
  }
}

:deep(.ant-form-item) {
  width: 604px;
  display: flex;

  .ant-form-item-control {
    width: 508px;
    margin-left: 4px;
    flex: unset;
  }

  .ant-form-item-label {
    flex-grow: 0;
    width: 80px;
    text-align: right;
  }
}

::v-deep(.groupSelect .ant-select) {
  width: 112px;
}

::v-deep(.statusSelect .ant-select) {
  width: 112px;
}

::v-deep(.move-item .ant-select) {
  width: 492px;
}

::v-deep(.ant-form-item-control-input-content:hover) {
  .anticon-close-circle {
    display: block;
  }

  .ant-input-show-count-suffix {
    // display: none;
  }
}
</style>
